package com.zte.ychr.controller.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zte.ychr.controller.BaseController;
import com.zte.ychr.service.recruit.RecruitResumeJobService;
import com.zte.ychr.util.ConfigUtil;
import com.zte.ychr.util.FileUpload;
import com.zte.ychr.util.WordExportUtil;

/**
 * 
 * 
 * @author 
 *
 */
@Controller
@RequestMapping("/upload")
public class FileUploadController extends BaseController{

	private String uploadRootPath =ConfigUtil.getPropertie("file.uploadRootPath");
	private String downloadPathRoot="upload/download/";
	
	private String replaceCharNew="$";
	private String replaceCharOld=".";
	
	@Resource
    private RecruitResumeJobService recruitResumeJobService;
	
	/**
	 * 文件上传
	 * 
	 * @param file
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toFileUpload")
	public String toFileUpload() {
		return "file/fileUpload";
		
	}
	
	/**
	 * 文件上传
	 * 
	 * @param file
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/fileUpload")
	@ResponseBody
	public Map fileUpload(@RequestParam("Filedata") MultipartFile file, HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		String fileName = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();//文件存放名
		FileUpload.fileUp(file,uploadRootPath, fileName);
		
		String extName = getExtName(file);//后缀名
		String fileRealName = getName(file);//文件名
		String fileRealFullName = fileRealName+extName;//文件全名
		String downloadPath = downloadPathRoot+fileName+extName.replace(replaceCharOld, replaceCharNew);//下载路径
		
		/*response.setContentType("application/json;charset=UTF-8");*/
		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("fileSize", file.getSize());
		retMap.put("status", 200);
		retMap.put("fileRealName", fileRealName);
		retMap.put("fileRealFullName", fileRealFullName);
		retMap.put("downloadPath", downloadPath);
		/*String json = JSONUtils.toJSONString(retMap);
		response.getOutputStream().write(json.getBytes());*/
		return retMap;
	}
	
	/**
	 * 文件上传
	 * 
	 * @param file
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/download/{fileName}/{fileRealName}")
	@ResponseBody
	public void download(@PathVariable String fileName,@PathVariable String fileRealName,HttpServletRequest request,HttpServletResponse response) throws Exception {
		if (StringUtils.isNotBlank(fileName)) {
			String fileNameTemp=fileName.replace(replaceCharNew,replaceCharOld);
			File file=new File(uploadRootPath,fileNameTemp);
		    String filename = file.getName();// 获取日志文件名称
		    InputStream fis = new BufferedInputStream(new FileInputStream(file));
		    byte[] buffer = new byte[fis.available()];
		    fis.read(buffer);
		    fis.close();
		    response.reset();
		    String string ="";
		    if (StringUtils.isNotBlank(fileRealName)) {
		    	int idx = fileNameTemp.lastIndexOf(replaceCharOld);
		    	if (idx != -1) {
		    		string = fileRealName+fileNameTemp.substring(idx);
				}
			}else{
				 string = new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1");
			}
		    // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
			response.addHeader("Content-Disposition", "attachment;filename=" + string);
		    response.addHeader("Content-Length", "" + file.length());
		    OutputStream os = new BufferedOutputStream(response.getOutputStream());
		    response.setContentType("application/octet-stream");
		    os.write(buffer);// 输出文件
		    os.flush();
		    os.close();
		}
		
	}
	/**
     * 简历下载
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/downResume/{resumeId}")
    @ResponseBody
    public void downResume(@PathVariable String resumeId,HttpServletRequest request,HttpServletResponse response) throws Exception {
        if (StringUtils.isNotBlank(resumeId)) {
            // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
            response.addHeader("Content-Disposition", "attachment;filename=" + resumeId+".doc");
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            recruitResumeJobService.exportRusume(resumeId, os);
        }
        
    }
	private String getExtName(MultipartFile file) {
		int idx = file.getOriginalFilename().lastIndexOf('.');
		if (idx != -1) {
			return file.getOriginalFilename().substring(idx);
		}
		return "";
	}

	private String getName(MultipartFile file) throws UnsupportedEncodingException {
		int idx = file.getOriginalFilename().lastIndexOf('.');
		if (idx != -1) {
			return file.getOriginalFilename().substring(0, idx);
		}
		return "";
	}

}